// src/main/java/com/example/musicplayer/MusicFragment.kt
package com.example.musicplayer

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.musicplayer.dao.CategoryDAO
import com.example.musicplayer.dao.MusicDAOImpl
import com.example.musicplayer.model.Song
import com.example.musicplayer.model.SongCategory
import java.io.IOException
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.widget.ImageView
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.example.musicplayer.util.HistoryManager

class MusicFragment : Fragment(), SongCategoryAdapter.OnItemClickListener {

    private lateinit var drawerLayout: DrawerLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var songCategoryAdapter: SongCategoryAdapter
    private lateinit var categoryDAO: CategoryDAO
    private lateinit var titleTextView: TextView
    private lateinit var musicNameTextView: TextView
    private lateinit var musicSingerTextView: TextView
    private lateinit var musicImageView: ImageView
    private lateinit var seekBar: SeekBar
    private lateinit var prevButton: ImageButton
    private lateinit var playPauseButton: ImageButton
    private lateinit var nextButton: ImageButton
    private lateinit var musicDAO: MusicDAOImpl
    private lateinit var mediaPlayer: MediaPlayer
    private lateinit var currentTimeTextView: TextView
    private lateinit var totalTimeTextView: TextView
    private var currentSong: Song? = null
    private var currentCategory: SongCategory? = null
    private var currentSongIndex = 0
    private val handler = Handler(Looper.getMainLooper())
    private var isPreparing = false
    private val runnable = object : Runnable {
        override fun run() {
            if (mediaPlayer.isPlaying) {
                seekBar.progress = mediaPlayer.currentPosition
                updateCurrentTimeText()
            }
            handler.postDelayed(this, 1000)
        }
    }
    private lateinit var prefs: SharedPreferences

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_music, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        drawerLayout = view.findViewById(R.id.drawer_layout)
        recyclerView = view.findViewById(R.id.recycler_view)
        titleTextView = view.findViewById(R.id.title_text_view)
        musicNameTextView = view.findViewById(R.id.music_name)
        musicSingerTextView = view.findViewById(R.id.music_singer)
        musicImageView = view.findViewById(R.id.music_img)
        seekBar = view.findViewById(R.id.seekBar)
        prevButton = view.findViewById(R.id.prev_music)
        playPauseButton = view.findViewById(R.id.play_pause)
        nextButton = view.findViewById(R.id.next_music)
        currentTimeTextView = view.findViewById(R.id.currentTimeTextView)
        totalTimeTextView = view.findViewById(R.id.totalTimeTextView)

        val selectorButton = view.findViewById<ImageButton>(R.id.selector)

        // 初始化 SharedPreferences
        prefs = requireActivity().getPreferences(Context.MODE_PRIVATE)

        // 初始化 CategoryDAO 和 MusicDAO
        categoryDAO = CategoryDAO(requireContext())
        musicDAO = MusicDAOImpl(requireContext())

        // 获取所有歌曲类别
        val songCategories = categoryDAO.getAllSongCategories()

        // 设置 RecyclerView
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        songCategoryAdapter = SongCategoryAdapter(songCategories, this)
        recyclerView.adapter = songCategoryAdapter

        // 设置按钮点击事件
        selectorButton.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.START)
        }

        // 初始化 MediaPlayer
        mediaPlayer = MediaPlayer()
        mediaPlayer.setOnCompletionListener { mp ->
            Log.d("MusicFragment", "MediaPlayer completed playing: ${currentSong?.title}")
            playNextSong()
        }

        // 设置 SeekBar 的监听器
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser && mediaPlayer.isPlaying) {
                    mediaPlayer.seekTo(progress)
                    updateCurrentTimeText()
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}

            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 设置播放/暂停按钮的点击事件
        playPauseButton.setOnClickListener {
            togglePlayPause()
        }

        // 设置上一首按钮的点击事件
        prevButton.setOnClickListener {
            playPreviousSong()
        }

        // 设置下一首按钮的点击事件
        nextButton.setOnClickListener {
            playNextSong()
        }

        setDefaultTitle()

        arguments?.let { args ->
            val song = args.getSerializable("song") as? Song
            if (song != null) {
                currentSong = song
                setSongInfo(song)
                playSong(song)
                currentCategory = currentSong?.categoryId?.let { categoryDAO.getSongCategoryById(it) }
                titleTextView.text = currentCategory?.name
            }
        }

        // 创建通知渠道
        createNotificationChannel(requireContext())

        // 检查并请求 POST_NOTIFICATIONS 权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), REQUEST_CODE_NOTIFICATIONS)
            }
        }
    }

    private fun setDefaultTitle() {
        val defaultCategory = categoryDAO.getSongCategoryById(1)
        if (defaultCategory != null) {
            titleTextView.text = defaultCategory.name
            updateSongInfo(defaultCategory.id)
        } else {
            titleTextView.text = "No Category Found"
        }
    }

    private fun updateSongInfo(categoryId: Int) {
        val songs = musicDAO.getSongsByCategoryId(categoryId)
        currentCategory = categoryDAO.getSongCategoryById(categoryId)
        currentSongIndex = 0

        if (songs.isNotEmpty()) {
            setSongInfo(songs[0])
            playSong(songs[0])
        } else {
            setSongInfo(null)
        }
    }

    private fun setSongInfo(song: Song?) {
        musicNameTextView.text = song?.title ?: "No Songs Found"
        musicSingerTextView.text = song?.artist ?: ""
        musicImageView.setImageBitmap(song?.image?.let { BitmapFactory.decodeByteArray(it, 0, it.size) } ?: R.drawable.ic_launcher_background.toBitmap())
    }

    private fun playSong(song: Song) {
        currentSong = song
        val songUri = Uri.parse(song.audioPath)

        try {
            if (mediaPlayer.isPlaying) {
                mediaPlayer.stop()
            }
            mediaPlayer.reset()
            mediaPlayer.setDataSource(requireContext(), songUri)

            // 设置准备完成的监听器
            mediaPlayer.setOnPreparedListener { mp ->
                isPreparing = false
                mp.start()
                seekBar.max = mp.duration
                seekBar.progress = 0
                handler.post(runnable)
                playPauseButton.setImageResource(R.drawable.stop)
                updateTotalTimeText()

                Log.d("MusicFragment", "Playing new song: ${song.title}")

                // 记录播放历史
                HistoryManager.saveSong(requireContext(), song)

                // 显示通知
                showSongNotification(requireContext(), song.title, song.image)
            }

            // 设置准备中的标志
            isPreparing = true

            // 开始异步准备
            mediaPlayer.prepareAsync()
        } catch (e: IOException) {
            e.printStackTrace()
            Log.e("MusicFragment", "Error playing song: ${song.title}", e)
        }
    }

    private fun playPreviousSong() {
        val songs = musicDAO.getSongsByCategoryId(currentCategory?.id ?: 1)
        if (songs.isNotEmpty()) {
            currentSongIndex = (currentSongIndex - 1 + songs.size) % songs.size
            setSongInfo(songs[currentSongIndex])
            playSong(songs[currentSongIndex])
        }
    }

    private fun playNextSong() {
        if (isPreparing) {
            Log.d("MusicFragment", "Skipping playNextSong because MediaPlayer is preparing")
            return
        }

        val songs = musicDAO.getSongsByCategoryId(currentCategory?.id ?: 1)
        if (songs.isNotEmpty()) {
            currentSongIndex = (currentSongIndex + 1) % songs.size
            setSongInfo(songs[currentSongIndex])
            playSong(songs[currentSongIndex])
            Log.d("MusicFragment", "Playing next song: ${songs[currentSongIndex].title}")
        } else {
            Log.d("MusicFragment", "No more songs to play")
        }
    }

    private fun updateCurrentTimeText() {
        val currentPosition = mediaPlayer.currentPosition
        val currentTime = formatTime(currentPosition)
        currentTimeTextView.text = currentTime
    }

    private fun updateTotalTimeText() {
        val totalDuration = mediaPlayer.duration
        val totalTime = formatTime(totalDuration)
        totalTimeTextView.text = totalTime
    }

    private fun formatTime(duration: Int): String {
        val minutes = duration / 1000 / 60
        val seconds = duration / 1000 % 60
        return String.format("%02d:%02d", minutes, seconds)
    }

    private fun togglePlayPause() {
        if (mediaPlayer.isPlaying) {
            mediaPlayer.pause()
            playPauseButton.setImageResource(R.drawable.play)
            Log.d("MusicFragment", "Pausing the song")
        } else {
            if (mediaPlayer.currentPosition > 0) {
                mediaPlayer.start()
                playPauseButton.setImageResource(R.drawable.stop)
                Log.d("MusicFragment", "Resuming the song")
            } else {
                Log.d("MusicFragment", "Media player is not ready to play")
            }
        }
    }

    override fun onItemClick(category: SongCategory) {
        drawerLayout.closeDrawer(GravityCompat.START)
        titleTextView.text = category.name
        updateSongInfo(category.id)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(runnable)
        mediaPlayer.release()
    }

    override fun onPause() {
        super.onPause()
        // 移除保存播放进度的代码
    }

    private fun Int.toBitmap(): Bitmap? {
        val drawable = ContextCompat.getDrawable(requireContext(), this)
        return drawable?.toBitmap()
    }

    private fun Drawable.toBitmap(): Bitmap {
        val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        setBounds(0, 0, canvas.width, canvas.height)
        draw(canvas)
        return bitmap
    }

    private fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "Music Service Channel"
            val descriptionText = "Channel for music service notifications"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel("music_channel", name, importance).apply {
                description = descriptionText
            }
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun showSongNotification(context: Context, songName: String, image: ByteArray?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                Log.w("MusicFragment", "POST_NOTIFICATIONS permission not granted, cannot show notification")
                return
            }
        }
        val fullScreenIntent = Intent(context, MusicFragment::class.java)
        val fullScreenPendingIntent = PendingIntent.getActivity(context, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

        val builder = NotificationCompat.Builder(context, "music_channel")
            .setSmallIcon(R.drawable.logo) // 替换为你的图标资源
            .setContentTitle("正在播放")
            .setContentText(songName)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setColor(ContextCompat.getColor(context, R.color.selected))
            .setFullScreenIntent(fullScreenPendingIntent, true)
            .setOngoing(false) // 如果希望通知持续显示，可以设置为 true
            .setAutoCancel(false) // 如果希望点击后不自动取消，可以设置为 false
            .setSound(null) // 确保通知没有声音
            .setCategory(Notification.CATEGORY_TRANSPORT) // 指示这是一个与媒体播放相关的通知

        // 设置大图标
        if (image != null) {
            val largeIcon = BitmapFactory.decodeByteArray(image, 0, image.size)
            builder.setLargeIcon(largeIcon)
        }

        with(NotificationManagerCompat.from(context)) {
            notify(1, builder.build()) // 1 是通知的 ID，可以自定义
        }
    }

    private val REQUEST_CODE_NOTIFICATIONS = 1001

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_NOTIFICATIONS) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，可以继续显示通知
                Log.d("MusicFragment", "POST_NOTIFICATIONS permission granted")
            } else {
                // 权限被拒绝，处理这种情况
                Log.d("MusicFragment", "POST_NOTIFICATIONS permission denied")
            }
        }
    }
}